import '../models/question.dart';
import '../services/database_service.dart';

class QuestionRepository {
  final DatabaseService _dbService = DatabaseService();
  static const String _tableName = DatabaseService.questionsTable;

  /// 添加题目
  Future<int> addQuestion(Question question) async {
    final data = question.toMap();
    data.remove('id'); // 移除id，让数据库自动生成
    return await _dbService.insert(_tableName, data);
  }

  /// 获取所有题目
  Future<List<Question>> getAllQuestions() async {
    final results = await _dbService.getAll(_tableName);
    return results.map((data) => Question.fromMap(data)).toList();
  }

  /// 根据ID获取题目
  Future<Question?> getQuestionById(int id) async {
    final result = await _dbService.getById(_tableName, id);
    return result != null ? Question.fromMap(result) : null;
  }

  /// 根据分类获取题目
  Future<List<Question>> getQuestionsByCategory(String category) async {
    final results = await _dbService.getByField(_tableName, 'category', category);
    return results.map((data) => Question.fromMap(data)).toList();
  }
  
  /// 根据分类和考点筛选题目
  Future<List<Question>> getQuestionsByFilters({String? category, String? keyPoint}) async {
    final allQuestions = await getAllQuestions();
    
    return allQuestions.where((question) {
      bool matchCategory = category == null || question.category == category;
      bool matchKeyPoint = keyPoint == null || question.keyPoint == keyPoint;
      return matchCategory && matchKeyPoint;
    }).toList();
  }

  /// 根据难度获取题目
  Future<List<Question>> getQuestionsByDifficulty(int difficulty) async {
    final results = await _dbService.getByField(_tableName, 'difficulty', difficulty);
    return results.map((data) => Question.fromMap(data)).toList();
  }

  /// 搜索题目
  Future<List<Question>> searchQuestions(String keyword) async {
    final allQuestions = await getAllQuestions();
    return allQuestions.where((question) => 
      question.question.toLowerCase().contains(keyword.toLowerCase()) ||
      question.explanation.toLowerCase().contains(keyword.toLowerCase())
    ).toList();
  }

  /// 根据标签搜索题目
  Future<List<Question>> getQuestionsByTag(String tag) async {
    final allQuestions = await getAllQuestions();
    return allQuestions.where((question) => 
      question.tags.toLowerCase().contains(tag.toLowerCase())
    ).toList();
  }

  /// 随机获取题目
  Future<List<Question>> getRandomQuestions(int count, {
    String? category,
    int? difficulty,
  }) async {
    List<Question> questions;
    
    if (category != null) {
      questions = await getQuestionsByCategory(category);
    } else if (difficulty != null) {
      questions = await getQuestionsByDifficulty(difficulty);
    } else {
      questions = await getAllQuestions();
    }
    
    questions.shuffle();
    return questions.take(count).toList();
  }

  /// 更新题目
  Future<void> updateQuestion(Question question) async {
    await _dbService.update(_tableName, question.toMap());
  }

  /// 删除题目
  Future<void> deleteQuestion(int id) async {
    await _dbService.delete(_tableName, id);
  }
  
  /// 删除所有题目
  Future<bool> deleteAllQuestions() async {
    try {
      await _dbService.clearTable(_tableName);
      return true;
    } catch (e) {
      print('删除所有题目失败: $e');
      return false;
    }
  }

  /// 批量添加题目
  Future<List<int>> addQuestions(List<Question> questions) async {
    final List<int> ids = [];
    for (final question in questions) {
      final id = await addQuestion(question);
      ids.add(id);
    }
    return ids;
  }

  /// 获取题目总数
  Future<int> getQuestionCount() async {
    return await _dbService.count(_tableName);
  }

  /// 获取分类列表
  Future<List<String>> getCategories() async {
    final allQuestions = await getAllQuestions();
    
    // 打印所有题目的分类，用于调试
    for (var question in allQuestions) {
      print('题目ID: ${question.id}, 分类: "${question.category}"');
    }
    
    final categories = allQuestions
        .map((question) => question.category)
        .where((category) => category.isNotEmpty)
        .toSet()
        .toList();
    
    // 打印最终的分类列表
    print('去重后的分类列表: $categories');
    
    categories.sort();
    return categories;
  }

  /// 获取所有标签
  Future<List<String>> getAllTags() async {
    final allQuestions = await getAllQuestions();
    final allTags = <String>{};
    
    for (final question in allQuestions) {
      if (question.tags.isNotEmpty) {
        final tags = question.tags.split(',').map((tag) => tag.trim());
        allTags.addAll(tags);
      }
    }
    
    final tagList = allTags.toList();
    tagList.sort();
    return tagList;
  }
  
  /// 获取所有考点
  Future<List<String>> getAllKeyPoints() async {
    final allQuestions = await getAllQuestions();
    final keyPoints = allQuestions
        .map((question) => question.keyPoint)
        .where((keyPoint) => keyPoint.isNotEmpty)
        .toSet()
        .toList();
    
    keyPoints.sort();
    return keyPoints;
  }
  
  /// 根据分类获取考点
  Future<List<String>> getKeyPointsByCategory(String category) async {
    final questions = await getQuestionsByCategory(category);
    final keyPoints = questions
        .map((question) => question.keyPoint)
        .where((keyPoint) => keyPoint.isNotEmpty)
        .toSet()
        .toList();
    
    keyPoints.sort();
    return keyPoints;
  }

  /// 获取难度分布统计
  Future<Map<int, int>> getDifficultyStats() async {
    final allQuestions = await getAllQuestions();
    final stats = <int, int>{};
    
    for (final question in allQuestions) {
      stats[question.difficulty] = (stats[question.difficulty] ?? 0) + 1;
    }
    
    return stats;
  }

  /// 获取分类统计
  Future<Map<String, int>> getCategoryStats() async {
    final allQuestions = await getAllQuestions();
    final stats = <String, int>{};
    
    for (final question in allQuestions) {
      if (question.category.isNotEmpty) {
        stats[question.category] = (stats[question.category] ?? 0) + 1;
      }
    }
    
    return stats;
  }

  /// 清空所有题目
  Future<void> clearAllQuestions() async {
    await _dbService.clearTable(_tableName);
  }
}